//
//  ChainNewsDetailVC.m
//  Chain
//
//  Created by zhaosh on 2018/4/10.
//  Copyright © 2018年 zhaosh. All rights reserved.
//

#import "ChainNewsDetailVC.h"
#import "WebViewJavascriptBridge.h"
#import "AFNetworking.h"
#import "GRMustache.h"
#import "DataInfo.h"
#import "ImageInfo.h"
#import "MJExtension.h"
#import "SDWebImageManager.h"
#import "Datetime.h"
#import "ChainNewsDetailBottomBar.h"
#import "ChainNewsBottomShareBar.h"
#import "ChainShareManager.h"
#import "ChainAccountManager.h"
#import "ChainLoginVC.h"

@interface ChainNewsDetailVC ()<UIWebViewDelegate>
@property (strong, nonatomic) UIWebView *webView;
@property (strong, nonatomic) NSString *detailID;
@property (strong, nonatomic) NSMutableArray *imagesArr;
@property (strong, nonatomic) NSMutableArray *MWPhotoArr;
@property (strong, nonatomic) WebViewJavascriptBridge *bridge;
@property (strong, nonatomic) DataInfo *dataInfo;
@end
@implementation ChainNewsDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setHeadView:self.view withLeftBtnText:@"chainBack" withHeadLable:@"辣头条" withRightBntText:@"detail_share1"];
    
    [self initUI];
    [self fetchListDataWithPage];
    [self initBridge];
}

- (void)initUI {
    self.view.backgroundColor = [UIColor whiteColor];
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height-50)];
    [self.webView setScalesPageToFit:YES];
    [self.view addSubview:self.webView];
    
    [self.webView setBackgroundColor:HEXCOLOR(@"#ededed")];
}

-(void)initBottomBar{
    __weak typeof(self) weakself=self;
    ChainNewsDetailBottomBar *bottomBar=[[ChainNewsDetailBottomBar alloc] initWithFrame:CGRectMake(0, self.view.height-50, self.view.width, 50) withCollect:self.dataInfo.isCollected];
    bottomBar.shareBlock = ^(UIButton *btn) {
         [weakself addAction];
    };
    bottomBar.collectBlock = ^(UIButton *btn) {
        if ([weakself.dataInfo.isCollected isEqualToString:@"1"]) {
           [weakself deleteCollectedNews:btn];
        }else{
           [weakself collectedNews:btn];
        }
    };
    bottomBar.commentBlock = ^(UIButton *btn) {
          [MBProgressHUD  showMessage:@"持续更新中···" ToView:nil RemainTime:0.8];
    };
    [self.view addSubview:bottomBar];
}

-(void)collectedNews:(UIButton *)btn{
     __weak typeof(self)weakSelf = self;
    NSDictionary *params = @{@"newsId":[NSString stringWithFormat:@"%@",self.dataInfo._id]};
    NSString *requestUrl=[NSString stringWithFormat:@"%@%@",BASE_URL,CollectedNews_Url];
    
    if (SESSION_ID) {
        [[ChainNetAPIClient sharedJsonClient]postRequestJsonDataWithPath:requestUrl withParams:params withHeader:nil andBlock:^(id data, NSError *error) {
            NSDictionary *info = [NSDictionary dictionaryWithDictionary:data];
            if (error) {
                NSString *message=[info objectForKey:@"message"];
                [MBProgressHUD  showMessage:message ToView:nil RemainTime:0.8];
            }else{
                NSString *status=[NSString stringWithFormat:@"%@",[info objectForKey:@"status"]];
                NSString *message=[info objectForKey:@"message"];
                NSString *errorCode=[NSString stringWithFormat:@"%@",[info objectForKey:@"errorCode"]];
                if([status isEqualToString:@"OK"]){
                    [btn setBackgroundImage:[UIImage imageNamed:@"detail_collect_selected"] forState:UIControlStateNormal];
                    weakSelf.dataInfo.isCollected =@"1";
                }else{
                    [MBProgressHUD  showMessage:message ToView:nil RemainTime:0.5];
                    if ([errorCode isEqualToString:@"0"]) {
                        [ChainAccountManager removeAccountCache];
                        [weakSelf pushLoginVC];
                    }
                }
            }
        }];
    }else{
        [self pushLoginVC];
    }
}

-(void)deleteCollectedNews:(UIButton *)btn{
    __weak typeof(self)weakSelf = self;
    NSDictionary *params = @{@"collectedIdList":@[self.dataInfo._id]};
    NSString *requestUrl=[NSString stringWithFormat:@"%@%@",BASE_URL,DeleteCollectedNews_Url];
    if (SESSION_ID) {
        [[ChainNetAPIClient sharedJsonClient]postRequestJsonDataWithPath:requestUrl withParams:params withHeader:nil andBlock:^(id data, NSError *error) {
            NSDictionary *info = [NSDictionary dictionaryWithDictionary:data];
            if (error) {
                NSString *message=[info objectForKey:@"message"];
                [MBProgressHUD  showMessage:message ToView:nil RemainTime:0.8];
            }else{
                NSString *status=[NSString stringWithFormat:@"%@",[info objectForKey:@"status"]];
                NSString *message=[info objectForKey:@"message"];
                NSString *errorCode=[NSString stringWithFormat:@"%@",[info objectForKey:@"errorCode"]];
                if([status isEqualToString:@"OK"]){
                    [btn setBackgroundImage:[UIImage imageNamed:@"detail_collect"] forState:UIControlStateNormal];
                    weakSelf.dataInfo.isCollected =@"0";
                }else{
                    [MBProgressHUD  showMessage:message ToView:nil RemainTime:0.5];
                    
                    if ([errorCode isEqualToString:@"0"]) {
                        [ChainAccountManager removeAccountCache];
                        [weakSelf pushLoginVC];
                    }
                }
            }
        }];
    }else{
        [self pushLoginVC];
    }
}

-(void)pushLoginVC{
    ChainLoginVC *vc=[[ChainLoginVC alloc] init];
    [self.navigationController pushViewController:vc animated:NO];
}

- (void)initBridge {
    // 开启日志
    [WebViewJavascriptBridge enableLogging];
    
    //设置给哪个webView建立js与oc通信的桥梁
    self.bridge = [WebViewJavascriptBridge bridgeForWebView:self.webView];
    //如果需要实现UIWebViewDelegate可以设置代理
    [self.bridge setWebViewDelegate:self];
    
    //注册 用于js主动调用oc
    [self.bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"我是js主动调用后的输出");
    }];
    
    //注册图片点击事件
    __weak typeof(self)weakSelf = self;
    [self.bridge registerHandler:@"tapImage" handler:^(id data, WVJBResponseCallback responseCallback) {
        //点击图片的index
        NSLog(@"=======%@=========", data);
        NSString *index = (NSString *)data;
        [weakSelf browseImages:index.integerValue];
    }];
    
    //oc主动调用js
    [self.bridge callHandler:@"testJavascriptHandler" data:nil responseCallback:^(id responseData) {
        NSLog(@"我是oc主动调用js后的输出");
    }];
}

//初始化图片浏览器
- (void)browseImages:(NSInteger)index {
    if (index==1) {
        [self shareWithType:1];
    }else if (index==2){
        [self shareWithType:2];
    }else if (index==3){
        [self shareWithType:3];
    }else if (index==4){
        self.detailId =self.dataInfo.nextId;
        [self fetchListDataWithPage];
    }
}

-(void)fetchListDataWithPage{
    NSDictionary *params = @{@"id":self.detailId};
    __weak typeof(self)weakSelf = self;
    [self showLoading];
    
    NSString *requestUrl=[NSString stringWithFormat:@"%@%@",BASE_URL,@"/latoutiao/news/getNewsDetailInfo"];
    [[ChainNetAPIClient sharedJsonClient]postRequestJsonDataWithPath:requestUrl withParams:params withHeader:nil andBlock:^(id data, NSError *error) {
        NSDictionary *info = [NSDictionary dictionaryWithDictionary:data];
        if (error) {
            NSString *message=[info objectForKey:@"message"];
            [MBProgressHUD  showMessage:message ToView:nil RemainTime:0.5];
        }else{
            NSString *success=[NSString stringWithFormat:@"%@",[info objectForKey:@"success"]];
            if ([success isEqualToString:@"1"]) {
                DataInfo *model = [DataInfo yy_modelWithDictionary:[data objectForKey:@"value"]];
                model.isCollected = [NSString stringWithFormat:@"%@",[data valueForKeyPath:@"map.isCollected"]];
                model.nextId = [NSString stringWithFormat:@"%@",[data valueForKeyPath:@"map.nextId"]];
                weakSelf.dataInfo =model;
                
                [weakSelf handleData:model];
                
                [weakSelf initBottomBar];
            }
        }
        [weakSelf hideHUDafterDelay:0.3];
    }];
}

- (void)handleData:(DataInfo *)data {
    if (!data) {
        NSLog(@"返回数据错误");
        return;
    }
    NSMutableString *allTitleStr = [self handleNewsTitle:data];
    NSString *bodyStr = [NSString stringWithString:data.styleContent];
    bodyStr = [bodyStr stringByReplacingOccurrencesOfRegex:@"IMG#LATOUTIAO" withString:@"http://10.11.8.30/img/"];
    
    NSString * str5 = [allTitleStr stringByAppendingString:bodyStr];
    NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"NewsHtml" ofType:@"html"];
    NSMutableString* appHtml = [NSMutableString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
    [appHtml replaceOccurrencesOfString:@"<p>mainnews</p>" withString:str5 options:NSCaseInsensitiveSearch range:[appHtml rangeOfString:@"<p>mainnews</p>"]];
    
    //编码图片
    UIImage *selectedImage1 = [UIImage imageNamed:@"wechat1"];
    UIImage *selectedImage2 = [UIImage imageNamed:@"wechat2"];
    UIImage *selectedImage3 = [UIImage imageNamed:@"weibo"];
    UIImage *selectedImage4 = [UIImage imageNamed:@"next_detail"];
    
    NSString *stringImage1 = [self htmlForJPGImage:selectedImage1 withTag:1];
    NSString *stringImage2 = [self htmlForJPGImage:selectedImage2 withTag:2];
    NSString *stringImage3 = [self htmlForJPGImage:selectedImage3 withTag:3];
    NSString *stringImage4 = [self htmlForJPGImage:selectedImage4 withTag:4];
    
    NSString *htmlTitleStr;
    if (![self.dataInfo.nextId isBlankString]) {
        htmlTitleStr =  [NSString stringWithFormat:@"<div style='width:260px' height=20px> <a>分享到</a>  %@  %@ %@</div>  %@",stringImage1,stringImage2,stringImage3,stringImage4];
    }else{
        htmlTitleStr =  [NSString stringWithFormat:@"<div style='width:260px' height=20px> <a>分享到</a>  %@  %@ %@</div>",stringImage1,stringImage2,stringImage3];
    }
   
    [appHtml appendString:htmlTitleStr];
   
    NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
    [self.webView loadHTMLString:appHtml baseURL:baseURL];
}


//处理新闻body中的图片
- (NSMutableString *)handleImageInNews:(DataInfo *)data {
    NSMutableString *bodyStr = [data.styleContent mutableCopy];
    
    [data.img enumerateObjectsUsingBlock:^(ImageInfo *info, NSUInteger idx, BOOL * _Nonnull stop) {
        NSRange range = [bodyStr rangeOfString:info.ref];
        NSArray *wh = [info.pixel componentsSeparatedByString:@"*"];
        CGFloat width = [[wh objectAtIndex:0] floatValue];
        CGFloat height = [[wh objectAtIndex:1] floatValue];
        
        //占位图
        NSString *loadingImg = [[NSBundle mainBundle] pathForResource:@"loading" ofType:@"png"];
        NSString *imageStr = [NSString stringWithFormat:@"<p style = 'text-align:center'><img onclick = 'didTappedImage(%lu);' src = %@ id = '%@' width = '%.0f' height = '%.0f' hspace='0.0' vspace ='5' style ='width:80%%;height:80%%;' /></p>", (unsigned long)idx, loadingImg, info.src, width, height];
        [bodyStr replaceOccurrencesOfString:info.ref withString:imageStr options:NSCaseInsensitiveSearch range:range];
        
    }];
    
    [self getImageFromDownloaderOrDiskByImageUrlArray:data.img];
    
    return bodyStr;
}


//处理title的拼接显示
- (NSMutableString *)handleNewsTitle:(DataInfo *)data {
    NSString *htmlTitleStr = @"<style type='text/css'> p.thicker{font-weight: 900}p.light{font-weight: 0}p{font-size: 108%}h2 {font-size: 120%}h3 {font-size: 80%}</style> <h2 class = 'thicker'>{{title}}</h2><h3>{{source}} {{ptime}}</h3>";
    
    NSString *dateStr= [Datetime dateStringWithDateStr:data.createTime DateFormat:@"YYYY-MM-dd HH:mm"];
    return [[GRMustacheTemplate renderObject:@{@"title" : data.title, @"source" : data.source, @"ptime" : dateStr} fromString:htmlTitleStr error:NULL] mutableCopy];
}

- (void)getImageFromDownloaderOrDiskByImageUrlArray:(NSArray *)imageArray {
    SDWebImageManager *imageManager = [SDWebImageManager sharedManager];
    self.imagesArr = [NSMutableArray array];
    __weak typeof(self)weakSelf = self;
    for (ImageInfo *info in imageArray) {
        NSURL *imageUrl = [NSURL URLWithString:info.src];
        [self.imagesArr addObject:imageUrl];
        [imageManager diskImageExistsForURL:imageUrl completion:^(BOOL isInCache) {
            isInCache ? [weakSelf handleExistCache:imageUrl] : [weakSelf handleNotExistCache:imageUrl];
        }];
    }
}

//编码图片
- (NSString *)htmlForJPGImage:(UIImage *)image withTag:(NSInteger)tag
{
    NSData *imageData = UIImageJPEGRepresentation(image,1.0);
    NSString *imageSource = [NSString stringWithFormat:@"data:image/png;base64,%@",[imageData base64Encoding]];
    if (tag==4) {
         return [NSString stringWithFormat:@"<img onclick = 'didTappedImage(%lu);' src = \"%@\"  width=56px height=12px align=right vertical-align:bottom  hspace ='10'/>",tag,imageSource];
    }
    return [NSString stringWithFormat:@"<img onclick = 'didTappedImage(%lu);' src = \"%@\"  width=20px height=20px vertical-align:bottom  hspace ='10'/>",tag,imageSource];
}

//已经有图片缓存
- (void)handleExistCache:(NSURL *)imageUrl {
    SDWebImageManager *imageManager = [SDWebImageManager sharedManager];
    NSString *cacheKey = [imageManager cacheKeyForURL:imageUrl];
    NSString *imagePath = [imageManager.imageCache defaultCachePathForKey:cacheKey];
    
    NSString *sendData = [NSString stringWithFormat:@"replaceimage%@,%@", imageUrl.absoluteString, imagePath];
    [self.bridge callHandler:@"replaceImage" data:sendData responseCallback:^(id responseData) {
        NSLog(@"%@", responseData);
    }];
}

//本地没有图片缓存
- (void)handleNotExistCache:(NSURL *)imageUrl {
    SDWebImageManager *imageManager = [SDWebImageManager sharedManager];
    __weak typeof(self)weakSelf = self;
    
    [imageManager loadImageWithURL:imageUrl options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        
    } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
        if (image && finished) {
            NSLog(@"下载成功");
            [weakSelf handleExistCache:imageUrl];
        } else {
            NSLog(@"图片下载失败");
        }
    }];
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addAction{
    if (SESSION_ID) {
        NSArray *icons = @[@"share_friend",@"share_chat",@"share_weibo"];
        ChainNewsBottomShareBar *bottomV = [[ChainNewsBottomShareBar alloc] initWithFrame:self.view.bounds iconsArr:icons titles:nil];
        
        UIWindow *w = [UIApplication sharedApplication].keyWindow;
        [w addSubview:bottomV];
        
        self.fd_interactivePopDisabled = YES;
        __weak typeof(self) weakSelf = self;
        bottomV.closeBlock = ^{
            weakSelf.fd_interactivePopDisabled = NO;
        };
        bottomV.clickedBlock = ^(NSInteger index) {
            switch (index) {
                case 0:{
                   [self shareWithType:1];
                    break;
                }
                case 1:{
                   [self shareWithType:2];
                    break;
                }
                case 2:{
                    [self shareWithType:3];
                    break;
                }
                default:
                    break;
            }
        };
    }else{
        [self pushLoginVC];
    }
   
}

-(void)shareWithType:(NSInteger)type{
    NSString *shareUrl=[NSString stringWithFormat:@"%@/index.html?id=%@",BASE_URL,self.detailId];
    if (type==1) {
        
        [[ChainShareManager shareChainShareManager] shareWebPageToPlatformType:UMSocialPlatformType_WechatTimeLine
                                                                 andShareTitle:self.dataInfo.title
                                                                  andShareText:self.dataInfo.abstracts
                                                                   andShareUrl:shareUrl
                                                               andSuccessBlock:^(id data) {
                                                                   
                                                               } andFailBlock:^(NSError *error) {
                                                                   
                                                               }];
    }else if (type==2){
        [[ChainShareManager shareChainShareManager] shareWebPageToPlatformType:UMSocialPlatformType_WechatSession
                                                                 andShareTitle:self.dataInfo.title
                                                                  andShareText:self.dataInfo.abstracts
                                                                   andShareUrl:shareUrl
                                                               andSuccessBlock:^(id data) {
                                                                   
                                                               } andFailBlock:^(NSError *error) {
                                                                   
                                                               }];
    }else{
        [[ChainShareManager shareChainShareManager] shareWebPageToPlatformType:UMSocialPlatformType_Sina
                                                                 andShareTitle:self.dataInfo.title
                                                                  andShareText:self.dataInfo.abstracts
                                                                   andShareUrl:shareUrl
                                                               andSuccessBlock:^(id data) {
                                                                   
                                                               } andFailBlock:^(NSError *error) {
                                                                   
                                                               }];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
